package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.BadphenoService;
import com.indusfo.spc.vo.HintMessage;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.service.impl
 * @ClassName: BadphenoServiceImpl
 * @Author: 熊冰
 * @Description: 不良现象 业务层
 * @Date: 2019/8/20 15:53
 * @Version: 1.0
 */
@Service
public class BadphenoServiceImpl implements BadphenoService {
    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(BadphenoServiceImpl.class);

    @Resource
    private BadphenoMapper badphenoMapper;
    @Resource
    private BadphenoTypeMapper badphenoTypeMapper;
    @Resource
    private BadphenoProMapper badphenoProMapper;

    //查询
    @Override
    public JSONObject listBadpheno(Badpheno badpheno) {
        try {
            // 获取一页显示多少行
            Integer pagesize = badpheno.getPagesize();
            // 获取查询第几页
            Integer pageindex = badpheno.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            Integer badphenoTypeId = null;
            if (badpheno.getBadphenoTypeId() != null) {
                badphenoTypeId = badpheno.getBadphenoTypeId();
            }
            //是否有类型
            System.out.println(badphenoTypeId);
            //无类型查询第一个类型数据
//            if (badphenoTypeId == null) {
//                //获取第一个数据
//                BadphenoType badphenoType = new BadphenoType();
//                badphenoType.setBadphenoTypePid(0);
//                List<BadphenoType> badphenoTypeList = badphenoTypeMapper.selectAllBadphenoType(badphenoType);
//                if (badphenoTypeList != null && badphenoTypeList.size() >= 1) {
//                	badphenoType = badphenoTypeList.get(0);
//                }
//                //生成树
//                //查询全部
//                List<BadphenoType> list = badphenoTypeMapper.selectAllBadphenoType(new BadphenoType());
//                List<XTreeNode> treelist = new ArrayList<>();
//                //将树放入list
//                for (BadphenoType _MouldType : list) {
//                    XTreeNode node = new XTreeNode();
//                    node.setId(_MouldType.getBadphenoTypeId());
//                    node.setpId(_MouldType.getBadphenoTypePid());
//                    node.setTitle(_MouldType.getBadphenoTypeName());
//                    treelist.add(node);
//                }
//                //获取子类
//                XTreeUtil xTreeUtil = new XTreeUtil(badphenoType.getBadphenoTypeId(), treelist);
//                List<Integer> childs=xTreeUtil.getChilds();
//                List<Badpheno> listForPage = badphenoMapper.queryListBadpheno(badpheno, childs);
//                Integer count = badphenoMapper.countListBadpheno(badpheno, childs);
//                return JSONObject.oK(listForPage, count);
//            } else {
            if (badphenoTypeId == null || badphenoTypeId == 0) {
                //全查
                badpheno.setBadphenoTypeId(null);
                List<Badpheno> listForPage = badphenoMapper.selectAllBadpheno(badpheno);
                if (pagesize != null && pageindex != null) {
                    Integer count = badphenoMapper.countBadpheno(badpheno);
                    return JSONObject.oK(listForPage, count);
                } else {
                    return JSONObject.oK(listForPage.get(0));
                }
            } else {
                List<BadphenoType> list = badphenoTypeMapper.selectAllBadphenoType(new BadphenoType());
                List<XTreeNode> treelist = new ArrayList<>();
                for (BadphenoType _MouldType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_MouldType.getBadphenoTypeId());
                    node.setpId(_MouldType.getBadphenoTypePid());
                    node.setTitle(_MouldType.getBadphenoTypeName());
                    treelist.add(node);
                }
                XTreeUtil xTreeUtil = new XTreeUtil(badphenoTypeId, treelist);
                List<Integer> childs = xTreeUtil.getChilds();
                List<Badpheno> listForPage = badphenoMapper.queryListBadpheno(badpheno, childs);
                Integer count = badphenoMapper.countListBadpheno(badpheno, childs);
                return JSONObject.oK(listForPage, count);
            }
//            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //新增
    @Override
    public JSONObject insertOrUpdateBadpheno(Badpheno badpheno) {
        try {
            if (badpheno.getBadphenoTypeId() == null) {
                badpheno.setBadphenoTypeId(0);
            }
            if (badpheno.getDataState() == null) {
                badpheno.setDataState(1);
            }
            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(badpheno);
            if (checkParamsNotRepeatJson.isOk()) {
                if (badpheno.getBadphenoId() != null) {// 有id,做更新
                    validate(badpheno);
                    Integer row = badphenoMapper.updateByPrimaryKeySelective(badpheno);
                    if (row == 0) {
                        throw new ModifyFailedException("编辑不良现象失败");
                    }
                    return JSONObject.oK("编辑成功", row);
                } else {// 没id,做新增
                    // 校验传入参数
                    validate(badpheno);
                    Integer row = badphenoMapper.insertSelective(badpheno);
                    if (row == 0) {
                        throw new ModifyFailedException("新增不良现象失败");
                    }
                    return JSONObject.oK("新增成功", row);
                }
            } else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除
    @Override
    @Transactional
    public JSONObject deleteBadpheno(Long[] badphenoIds, Integer dataState) {
        //1.校验
        if (badphenoIds == null) {
            throw new ParamsErrorException("不良现象id不能为空");
        }
        if (dataState == null) {
            throw new ParamsErrorException("不良现象状态不能为空");
        }
        // 判断采集项目是否使用不良现象
        if(dataState == 2  ||  dataState == 3){
            int rows = badphenoMapper.selectDete(badphenoIds);
            if(rows > 0){
                return JSONObject.build(500,HintMessage.DETE_USE);
            }
        }
        int row = badphenoMapper.deleteBadpheno(badphenoIds, dataState);
        if(dataState == 2) {
        	// 联动删除
        	for (Long badphenoId : badphenoIds) {
        		badphenoMapper.deleteAllBadphenoBadcauseByBadpheno(badphenoId.intValue());
        		badphenoMapper.deleteAllBadphenoBadreplyByBadpheno(badphenoId.intValue());
        		badphenoProMapper.delAllProByBadpheno(badphenoId.intValue());
        	}
        }
        String msg = "";
        switch (dataState) {
            case 1:
                msg = "启用";
                break;
            case 2:
                msg = "删除";
                break;
            case 3:
                msg = "停用";
        }
        if (row == 0) {
            // 判断传入的数据状态参数dataState,返回相应信息
            switch (dataState) {
                case 1:
                    throw new ModifyFailedException(msg + "失败");
                case 2:
                    throw new ModifyFailedException(msg + "失败");
                case 3:
                    throw new ModifyFailedException(msg + "失败");
            }
        }
        return JSONObject.oK(msg + "成功", row);
    }

    //添加不良原因
    @Override
    public JSONObject insertBadphenoBadcause(Long[] ids, Integer badphenoId) {
        try {
            if (badphenoId == null || badphenoId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = badphenoMapper.insertBadphenoBadcause(ids, badphenoId);
                return JSONObject.oK("新增成功", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除不良原因
    @Override
    public JSONObject deleteBadphenoBadcause(Long[] ids, Integer badphenoId) {
        try {
            if (badphenoId == null || badphenoId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = badphenoMapper.deleteBadphenoBadcause(ids, badphenoId);
                return JSONObject.oK("删除成功", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //添加不良对策
    @Override
    public JSONObject insertBadphenoBadreply(Long[] ids, Integer badphenoId) {
        try {
            if (badphenoId == null || badphenoId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = badphenoMapper.insertBadphenoBadreply(ids, badphenoId);
                return JSONObject.oK("新增成功", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除不良对策
    @Override
    public JSONObject deleteBadphenoBadreply(Long[] ids, Integer badphenoId) {
        try {
            if (badphenoId == null || badphenoId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = badphenoMapper.deleteBadphenoBadreply(ids, badphenoId);
                return JSONObject.oK("删除成功", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //查询不良原因关联
    @Override
    public JSONObject selectBadphenoBadcause(Badpheno badpheno) {
        try {
            // 获取一页显示多少行
            Integer pagesize = badpheno.getPagesize();
            // 获取查询第几页
            Integer pageindex = badpheno.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            List<Badcause> listForPage = badphenoMapper.selectBadphenoBadcause(badpheno);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据", listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = badphenoMapper.countBadphenoBadcause(badpheno);
                return JSONObject.oK("查询成功", listForPage, count);
            }
            return JSONObject.oK("查询成功", listForPage.get(0), 1);
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //查询不良对策关联
    @Override
    public JSONObject selectBadphenoBadreply(Badpheno badpheno) {
        try {
            // 获取一页显示多少行
            Integer pagesize = badpheno.getPagesize();
            // 获取查询第几页
            Integer pageindex = badpheno.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            List<Badreply> listForPage = badphenoMapper.selectBadphenoBadreply(badpheno);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据", listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = badphenoMapper.countBadphenoBadreply(badpheno);
                return JSONObject.oK("查询成功", listForPage, count);
            }
            return JSONObject.oK("查询成功", listForPage.get(0), 1);

        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //全查不良对策
    @Override
    public JSONObject queryBadreply(Badpheno badpheno) {
//        List<Badreply> listBlxxBldc = null;
        List<Badreply> listBadreply = null;
        try {
            // 获取一页显示多少行
            Integer pagesize = badpheno.getPagesize();
            // 获取查询第几页
            Integer pageindex = badpheno.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            if (badpheno.getBadphenoId() != null) {  //如果有不良对策id,则查询单个不良对策
                //不良现象已有数据
                listBadreply = badphenoMapper.queryBadreply(badpheno);
                System.out.println(badpheno.getPageindex() + "+" + badpheno.getPagesize());
            } else {
                throw new ParamsErrorException("不良现象ID不能为空");
            }
            //查询分页总记录数
            int count = badphenoMapper.countBadreply(badpheno); //返回查询到的总记录数
            if (listBadreply.isEmpty()) {
                return JSONObject.oK("没有不良对策相关数据", listBadreply, count);
            }
            return JSONObject.oK("查询成功", listBadreply, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    //全查不良原因
    @Override
    public JSONObject queryBadcause(Badpheno badpheno) {
//        List<Badcause> listBlxxBlyy = null;
        List<Badcause> listBadcause = null;
        try {
            // 获取一页显示多少行
            Integer pagesize = badpheno.getPagesize();
            // 获取查询第几页
            Integer pageindex = badpheno.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            if (badpheno.getBadphenoId() != null) {  //如果有不良对策id,则查询单个不良对策
                //不良现象已有数据
                listBadcause = badphenoMapper.queryBadcause(badpheno);
            } else {
                throw new ParamsErrorException("不良现象ID不能为空");
            }
            //查询分页总记录数
            int count = badphenoMapper.countBadcause(badpheno);  //返回查询到的总记录数
            if (listBadcause.isEmpty()) {
                return JSONObject.oK("没有不良原因相关数据", listBadcause, count);
            }
            return JSONObject.oK("查询成功", listBadcause, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject queryPro(BadphenoPro badphenoPro) {
        try {
            // 获取一页显示多少行
            Integer pagesize = badphenoPro.getPagesize();
            // 获取查询第几页
            Integer pageindex = badphenoPro.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badphenoPro.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            List<BadphenoPro> listForPage = badphenoProMapper.selectPro(badphenoPro);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有相关数据", listForPage, 0);
            }
            // 查询有多少条数据条数
            Integer count = badphenoProMapper.countPro(badphenoPro);
            return JSONObject.oK("查询成功", listForPage, count);

        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }

    }

    @Override
    public JSONObject insertPro(Long[] ids, Integer badphenoId) {
        try {
            if (badphenoId == null || badphenoId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } /*else if(ids==null || ids.length==0){
                return JSONObject.oK("新增成功", null);
            }*/ else {
                int row = badphenoProMapper.insertPro(ids, badphenoId);
                return JSONObject.oK("新增成功", row);
            }
        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    @Override
    public JSONObject deletePro(Long[] ids, Integer badphenoId) {
        try {
            if (badphenoId == null || badphenoId == 0) {
                throw new ParamsErrorException("不良现象id不能为空");
            } else {
                int row = badphenoProMapper.delPro(ids, badphenoId);
                return JSONObject.oK("删除成功", row);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //验证重复
    private JSONObject checkParamsNotRepeat(Badpheno badpheno) {
        try {
            // 判断不良原因类型ID是否传入
            if (badpheno.getBadphenoTypeId() == null || badpheno.getBadphenoTypeId() == 0) {
                throw new ParamsErrorException("未传入不良原因ID");
            } else {
                Badpheno check = new Badpheno();
                check.setBadphenoName(badpheno.getBadphenoName());
                if (badpheno.getBadphenoId() != null) {
                    // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                    check.setBadphenoId(badpheno.getBadphenoId());
                    int row = badphenoMapper.countParamsNotRepeat(check);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品");
                    }
                } else {
                    int row = badphenoMapper.countParamsNotRepeat(check);
                    if (row > 0) {
                        throw new ParamsErrorException("已存在该产品");
                    }
                }
                return JSONObject.oK();
            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //非空判断
    private void validate(Badpheno badpheno) {
        //现象名称
        String badphenoName = badpheno.getBadphenoName();
        if (StringUtils.isEmpty(badphenoName)) {
            throw new ParamsErrorException("名称不能为空");
        }
        if (badphenoName.getBytes().length > 50) {
            throw new ParamsErrorException("不良现象名称过长");
        }
        String remark = badpheno.getRemark();
        if (remark != null) {
            if (remark.getBytes().length > 100) {
                throw new ParamsErrorException("说明过长");
            }
        }
        //类型id
        Integer badphenoTypeId = badpheno.getBadphenoTypeId();
        if (badphenoTypeId == null) {
            throw new ParamsErrorException("不良原因类型不能为空");
        }
    }

    /**
     * 去添加查询（产品，任务单，批次）
     */
    @Override
    public JSONObject queryListBadphenoToInsert(Badpheno badpheno) {

        try {
            // 获取一页显示多少行
            Integer pagesize = badpheno.getPagesize();
            // 获取查询第几页
            Integer pageindex = badpheno.getPageindex();
            //初始值
            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            Integer badphenoTypeId = null;
            if (badpheno.getBadphenoTypeId() != null) {
                badphenoTypeId = badpheno.getBadphenoTypeId();
            }
            if (badphenoTypeId == null || badphenoTypeId == 0) {
                //全查
                badpheno.setBadphenoTypeId(null);
                List<Badpheno> listForPage = badphenoMapper.queryListBadphenoToInsert(badpheno);
                if (pagesize != null && pageindex != null) {
                    Integer count = badphenoMapper.countBadphenoToInsert(badpheno);
                    return JSONObject.oK(listForPage, count);
                } else {
                    return JSONObject.oK(listForPage.get(0));
                }
            } else {
                List<BadphenoType> list = badphenoTypeMapper.selectAllBadphenoTypeToInsert(new BadphenoType());
                List<XTreeNode> treelist = new ArrayList<>();
                for (BadphenoType _MouldType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_MouldType.getBadphenoTypeId());
                    node.setpId(_MouldType.getBadphenoTypePid());
                    node.setTitle(_MouldType.getBadphenoTypeName());
                    treelist.add(node);
                }
                XTreeUtil xTreeUtil = new XTreeUtil(badphenoTypeId, treelist);
                List<Integer> childs = xTreeUtil.getChilds();
                List<Badpheno> listForPage = badphenoMapper.queryListBadphenoToInserts(badpheno, childs);
                Integer count = badphenoMapper.countListBadphenoToInserts(badpheno, childs);
                return JSONObject.oK(listForPage, count);
            }
        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }

       /* try {
            //获取页面的数据个数
            Integer pagesize = badpheno.getPagesize();
            //获取查询的页数
            Integer pageindex = badpheno.getPageindex();
            if (pagesize != null && pageindex != null) {
                badpheno.setIncept(pagesize * (pageindex - 1));
            }
            //执行查询操作
            List<Badpheno> badphenoList = badphenoMapper.queryListBadphenoToInsert(badpheno);

            //如果页数和页面数量都不为空的情况下进行计数
            if (badphenoList.isEmpty()) {
                return JSONObject.oK(HintMessage.QUERY_NULL, badphenoList, 0);
            } else {
                Integer count = badphenoMapper.countBadphenoToInsert(badpheno);
                return JSONObject.oK(HintMessage.QUERY_SUCCESS, badphenoList, count);
            }

        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());

        }*/
    }
}
